<?php

namespace App\Services\Product\UserService;

use App\Exceptions\UserException;
use App\Facades\UserManager;
use Cache;
use Carbon\Carbon;
use Cartalyst\Sentinel\Checkpoints\ThrottlingException;
use DB;
use Sentinel;

class UserService 
{

    /**
     * 登录
     * @param  [type] $credentials 
     * @return [type]              
     */
    public function login($credentials)
    {
        try{

            $user = Sentinel::authenticate($credentials, true);
            if(!$user)
            {
                throw new UserException('login');
            }
        }catch(ThrottlingException $e){
            throw new UserException('loginThroot', "登录失败次数太多，请".$e->getDelay()."s后再尝试登录");
        }
    }

    public function logout()
    {
        $user = $this->getLoginUser();
        Sentinel::logout($user, true);
    }

    /**
     * 获取登录用户
     * @return [type] 
     */
    public function getLoginUser()
    {
        return Sentinel::getuser();
    }

    /**
     * 增加管理员
     * @param [type] $userData  
     * @param [type] $adminInfo 
     */
    public function add($userData, $adminInfo)
    {
        try{
            $this->isAdmin();
            DB::transaction(function() use ($userData, $adminInfo) {
                $user = UserManager::addUser($userData);

                if(!$user)
                {
                    throw new UserException('add');
                }

                $role = Sentinel::findRoleByName('Observer');

                $role->users()->attach($user);
                UserManager::addAdminInfo(array_merge($adminInfo, ['user_id' => $user->id]));
            });
        }catch(Exception $e){
            throw new UserException('add');
        }
    }

    /**
     * 更新密码
     * @param  [type] $password    
     * @param  [type] $newPassword 
     * @return [type]              
     */
    public function updatePassword($password, $newPassword)
    {
        $user = $this->getLoginUser();
        if(!$user)
        {
            return redirect('admin/login');
        }
        if(!Sentinel::validateCredentials($user, ['password' => $password]))
        {
            throw new UserException('password');
        }
        Sentinel::update($user, ['password' => $newPassword]);
    }

    /**
     * 删除管理员
     * @param  [type] $username 
     * @return [type]           
     */
    public function delete($username)
    {
        $this->isAdmin();
        $user = Sentinel::findByCredentials(['username' => $username]);
        if(is_null($user))
        {
           throw new UserException('notFound') ;
        }
        $user->delete();
    }

    /**
     * 更新管理员信息
     * @param  [type] $userId 
     * @param  [type] $data   
     * @return [type]         
     */
    public function updateAdminInfo($userId, $data)
    {
        $user = $this->getLoginUser();
        if($user->id != $userId)
        {
            if(!$user->hasAccess(['admin']))
            {
                throw new UserException('admin');
            }
        }
        UserManager::updateAdminInfo($userId, $data);
    }

    /**
     * 是否管理员
     * @return boolean 
     */
    public function isAdmin()
    {
        $user = $this->getLoginUser();
        if(!$user->hasAccess(['admin'])){
            throw new UserException('admin');
        }
    }

    /**
     * 获取全部管理员信息
     * @return [type] 
     */
    public function getAllAdminInfo($user)
    {
        if(!$user->hasAccess(['admin'])){
            return $this->findAdminInfoById($user->id);
        }
        return UserManager::getAllAdminInfo();
    }

    /**
     * 更具用户 id 获取用户信息
     * @param  [type] $userId 
     * @return [type]         
     */
    public function userInfoFindByOpenId($opendId)
    {
        $wxUser = UserManager::getWxUserByOpenId($opendId);
        if(is_null($wxUser))
        {
            throw new UserException('notFound');
        }
        $wxUser->load(['userInfo' => function($query){
                     $query->select(['user_id', 'name', 'phone']);
                 }]);
        return $wxUser->userInfo;
    }

    /**
     * 根据 id 获取管理员信息
     * @param  [type] $id 
     * @return [type]     
     */
    public function findAdminInfoById($id)
    {
        $user = UserManager::getUserById($id);
        return $user->load('adminInfo');

    }



}
